package com.ustc.hewei.nettyrpc2_0.netty.client.loadBalance.impl;

import com.ustc.hewei.nettyrpc2_0.common.warp.ZkNode;
import com.ustc.hewei.nettyrpc2_0.netty.client.loadBalance.CommonLoadBalance;

import java.util.List;

/**
* @description: 基于权重的轮询(Nginx)
* @author hewei
* @date 2022/9/26 20:21
* @version 1.0
*/

public class RoundRobin implements CommonLoadBalance {
    @Override
    public ZkNode getService(List<ZkNode> zkNodeList) {
        int target = -1;
        int max = Integer.MIN_VALUE;
        int sum = 0;
        for (int i = 0; i < zkNodeList.size(); i++) {
            ZkNode zkNode = zkNodeList.get(i);

            // 这儿有点问题，在zkNode节点中根本不会去更新，只会更新自己缓存中的zkNode节点的cur值
            int cur = zkNode.getCur();

            int weight = zkNode.getWeight();
            sum += weight;
            zkNode.setCur(cur + weight);
            if (weight != 0 && cur > max) {
                target = i;
                max = cur;
            }
        }
        if (target < 0) return null;
        ZkNode zkNode = zkNodeList.get(target);
        zkNode.setCur(zkNode.getCur() - sum);
        return zkNode;
    }
}
